<template>
  <div class="outbound-prediction">
    <el-card class="prediction-card">
      <template #header>
        <div class="card-header">
          <span>出库预测管理</span>
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </div>
      </template>

      <!-- 商品选择 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="选择商品">
          <el-select v-model="searchForm.productId" placeholder="请选择商品" @change="onProductChange">
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="`${product.productName} (${product.productNo})`"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadProductInfo">加载商品信息</el-button>
        </el-form-item>
      </el-form>

      <!-- 商品信息卡片 -->
      <el-card v-if="productInfo" class="product-info-card" shadow="hover">
        <template #header>
          <span>商品信息</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="info-item">
              <label>商品名称：</label>
              <span>{{ productInfo.productName }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>商品编号：</label>
              <span>{{ productInfo.productNo }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>当前库存：</label>
              <span>{{ productInfo.current_Inventory }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <label>商品类型：</label>
              <span>{{ productInfo.productTypeId }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 预测功能区域 -->
      <div class="prediction-functions">
        <el-row :gutter="20">
          <!-- 数据生成 -->
          <el-col :span="8">
            <el-card class="function-card" shadow="hover">
              <template #header>
                <span>1. 生成汇总数据</span>
              </template>
              <el-form :model="summaryForm" label-width="100px">
                <el-form-item label="开始日期">
                  <el-date-picker
                    v-model="summaryForm.startDate"
                    type="date"
                    placeholder="选择开始日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item label="结束日期">
                  <el-date-picker
                    v-model="summaryForm.endDate"
                    type="date"
                    placeholder="选择结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="generateSummaryData" :loading="loading.summary">
                    生成汇总数据
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <!-- 特征生成 -->
          <el-col :span="8">
            <el-card class="function-card" shadow="hover">
              <template #header>
                <span>2. 生成特征数据</span>
              </template>
              <el-form :model="featureForm" label-width="100px">
                <el-form-item label="预测日期">
                  <el-date-picker
                    v-model="featureForm.date"
                    type="date"
                    placeholder="选择预测日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="generateFeatures" :loading="loading.features">
                    生成特征数据
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <!-- 模型训练 -->
          <el-col :span="8">
            <el-card class="function-card" shadow="hover">
              <template #header>
                <span>3. 训练模型</span>
              </template>
              <div class="training-info">
                <p>使用历史数据训练预测模型</p>
                <el-button type="success" @click="trainModel" :loading="loading.training">
                  开始训练
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 预测执行 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card class="function-card" shadow="hover">
              <template #header>
                <span>4. 执行预测</span>
              </template>
              <el-form :model="predictionForm" label-width="100px">
                <el-form-item label="预测日期">
                  <el-date-picker
                    v-model="predictionForm.date"
                    type="date"
                    placeholder="选择预测日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="warning" @click="executePrediction" :loading="loading.prediction">
                    执行预测
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <!-- 预测结果 -->
          <el-col :span="12">
            <el-card class="function-card" shadow="hover">
              <template #header>
                <span>预测结果</span>
              </template>
              <div v-if="predictionResult" class="prediction-result">
                <el-alert
                  :title="`预测出库数量: ${predictionResult.prediction}`"
                  type="success"
                  :closable="false"
                  show-icon
                />
                <div class="result-details">
                  <p><strong>预测日期：</strong>{{ predictionResult.date }}</p>
                  <p><strong>商品名称：</strong>{{ productInfo?.productName }}</p>
                  <p><strong>当前库存：</strong>{{ productInfo?.current_Inventory }}</p>
                </div>
              </div>
              <div v-else class="no-result">
                <el-empty description="暂无预测结果" />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 预测历史 -->
      <el-card class="history-card" shadow="hover" style="margin-top: 20px;">
        <template #header>
          <span>预测历史</span>
        </template>
        <el-table :data="predictionHistory" style="width: 100%" v-loading="loading.history">
          <el-table-column prop="featureDate" label="预测日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.featureDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="featureType" label="特征类型" width="100" />
          <el-table-column prop="modelVersion" label="模型版本" width="100" />
          <el-table-column prop="featureVector" label="特征向量" show-overflow-tooltip />
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { TZRead, TZWrite } from '@/http/interceptors'

// 类型定义
interface Product {
  id: number
  productName: string
  productNo: string
  current_Inventory: number
  productTypeId: number
}

interface PredictionResult {
  prediction: number
  date: string
}

interface PredictionHistory {
  featureDate: string
  featureType: string
  modelVersion: string
  featureVector: string
}

// 响应式数据
const searchForm = reactive({
  productId: null as number | null
})

const summaryForm = reactive({
  startDate: '',
  endDate: ''
})

const featureForm = reactive({
  date: ''
})

const predictionForm = reactive({
  date: ''
})

const loading = reactive({
  summary: false,
  features: false,
  training: false,
  prediction: false,
  history: false
})

const productList = ref<Product[]>([])
const productInfo = ref<Product | null>(null)
const predictionResult = ref<PredictionResult | null>(null)
const predictionHistory = ref<PredictionHistory[]>([])

// 方法
const loadProductList = async () => {
  try {
    const response = await TZRead.get('/api/Product/list')
    console.log('API响应:', response.data) // 添加调试日志
    // 根据实际返回的数据格式调整 - 数据在pageData字段中
    productList.value = response.data.pageData || []
    console.log('商品列表:', productList.value) // 添加调试日志
  } catch (error) {
    ElMessage.error('加载商品列表失败')
    console.error('加载商品列表错误:', error)
  }
}

const loadProductInfo = async () => {
  if (!searchForm.productId) {
    ElMessage.warning('请先选择商品')
    return
  }

  try {
    const response = await TZRead.get(`/api/Product/list?id=${searchForm.productId}`)
    console.log('商品信息API响应:', response.data) // 添加调试日志
    // 根据实际返回的数据格式调整 - 数据在pageData字段中
    const products = response.data.pageData || []
    productInfo.value = products.find((p: Product) => p.id === searchForm.productId) || null
    
    if (productInfo.value) {
      ElMessage.success('商品信息加载成功')
      loadPredictionHistory()
    } else {
      ElMessage.error('未找到商品信息')
    }
  } catch (error) {
    ElMessage.error('加载商品信息失败')
    console.error('加载商品信息错误:', error)
  }
}

const onProductChange = () => {
  productInfo.value = null
  predictionResult.value = null
  predictionHistory.value = []
}

const generateSummaryData = async () => {
  if (!searchForm.productId) {
    ElMessage.warning('请先选择商品')
    return
  }

  if (!summaryForm.startDate || !summaryForm.endDate) {
    ElMessage.warning('请选择开始和结束日期')
    return
  }

  loading.summary = true
  try {
    const response = await TZWrite.post('/api/Prediction/GenerateSummaryData', {
      productId: searchForm.productId,
      startDate: summaryForm.startDate,
      endDate: summaryForm.endDate
    })

    if (response.data.success) {
      ElMessage.success('汇总数据生成成功')
    } else {
      ElMessage.error(response.data.message || '汇总数据生成失败')
    }
  } catch (error) {
    ElMessage.error('汇总数据生成失败')
    console.error(error)
  } finally {
    loading.summary = false
  }
}

const generateFeatures = async () => {
  if (!searchForm.productId) {
    ElMessage.warning('请先选择商品')
    return
  }

  if (!featureForm.date) {
    ElMessage.warning('请选择预测日期')
    return
  }

  loading.features = true
  try {
    const response = await TZWrite.post('/api/Prediction/GenerateFeatures', {
      productId: searchForm.productId,
      date: featureForm.date
    })

    if (response.data.success) {
      ElMessage.success('特征数据生成成功')
      loadPredictionHistory()
    } else {
      ElMessage.error(response.data.message || '特征数据生成失败')
    }
  } catch (error) {
    ElMessage.error('特征数据生成失败')
    console.error(error)
  } finally {
    loading.features = false
  }
}

const trainModel = async () => {
  if (!searchForm.productId) {
    ElMessage.warning('请先选择商品')
    return
  }

  loading.training = true
  try {
    const response = await TZWrite.post('/api/Prediction/TrainModel', {
      productId: searchForm.productId
    })

    if (response.data.success) {
      ElMessage.success('模型训练成功')
    } else {
      ElMessage.error(response.data.message || '模型训练失败')
    }
  } catch (error) {
    ElMessage.error('模型训练失败')
    console.error(error)
  } finally {
    loading.training = false
  }
}

const executePrediction = async () => {
  if (!searchForm.productId) {
    ElMessage.warning('请先选择商品')
    return
  }

  if (!predictionForm.date) {
    ElMessage.warning('请选择预测日期')
    return
  }

  loading.prediction = true
  try {
    const response = await TZWrite.post('/api/Prediction/PredictOutbound', {
      productId: searchForm.productId,
      predictionDate: predictionForm.date
    })

    if (response.data.success) {
      predictionResult.value = {
        prediction: response.data.prediction as number,
        date: predictionForm.date
      } as PredictionResult
      ElMessage.success(`预测完成：${response.data.prediction}`)
    } else {
      ElMessage.error(response.data.message || '预测失败')
    }
  } catch (error) {
    ElMessage.error('预测失败')
    console.error(error)
  } finally {
    loading.prediction = false
  }
}

const loadPredictionHistory = async () => {
  if (!searchForm.productId) return

  loading.history = true
  try {
    const endDate = new Date().toISOString().split('T')[0]
    const startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
    
    const response = await TZWrite.get('/api/Prediction/GetPredictionHistory', {
      params: {
        productId: searchForm.productId,
        startDate: startDate,
        endDate: endDate
      }
    })

    if (response.data.success) {
      predictionHistory.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载预测历史失败:', error)
  } finally {
    loading.history = false
  }
}

const refreshData = () => {
  loadProductList()
  if (searchForm.productId) {
    loadProductInfo()
  }
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadProductList()
})
</script>

<style scoped>
.outbound-prediction {
  padding: 20px;
}

.prediction-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.product-info-card {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.info-item label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}

.prediction-functions {
  margin-bottom: 20px;
}

.function-card {
  height: 100%;
}

.training-info {
  text-align: center;
  padding: 20px 0;
}

.training-info p {
  margin-bottom: 15px;
  color: #666;
}

.prediction-result {
  padding: 10px 0;
}

.result-details {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.result-details p {
  margin: 5px 0;
}

.no-result {
  text-align: center;
  padding: 40px 0;
}

.history-card {
  margin-top: 20px;
}
</style> 